package time_task

import (
	. "chess_platform/internal/common"
	"fmt"
)

//金流方面的统计
func StatDayTrans(r map[int64]int64) error {
	return ForExecute(statDayTrans, RecordDayTrans, r[RecordDayTrans])
}
func statDayTrans(t int64) error {
	LogPc.Info("-----------------进入统计金流函数----------------------------")
	var send, cost, tableNum, roundNum int64
	o := NewDBOrm(DBChessLog)
	dayTrans := GetTableByTimestamp(TableDayTrans, t)
	if CheckTableIsExist(dayTrans) {
		//send为正数
		sqlSend := fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount))
		FROM
			%v
		WHERE
			amount > 0
	`, dayTrans)
		//cost掉的为负数
		sqlCost := fmt.Sprintf(`
        SELECT
			IF(SUM(amount) is NULL,0,SUM(amount))
		FROM
			%v
		WHERE
			amount < 0
	`, dayTrans)
		o.Raw(sqlSend).QueryRow(&send)
		o.Raw(sqlCost).QueryRow(&cost)
	}

	dayGame := GetTableByTimestamp(TableDayGame, t)
	//检查表是否存在
	if CheckTableIsExist(dayGame) {
		//开桌数,及小局数
		sqlGame := fmt.Sprintf(`
		SELECT
			COUNT(DISTINCT tid) AS table_num, COUNT(1) AS round_num
		FROM
			%v
	`, dayGame)
		o.Raw(sqlGame).QueryRow(&tableNum, &roundNum)
	}

	_, end := StartEndTimeByTimestamp(t)
	data := map[string]interface{}{
		"day":       end - 1, //固定好一天之内的时间,这样重复执行时不会插入新的记录
		"send":      send,
		"cost":      cost,
		"remain":    send + cost,
		"table_num": tableNum,
		"round_num": roundNum,
	}
	NewOrUpdateChessLog(data, TableDayTransStat, o)
	LogPc.Info("-----------------退出统计金流函数----------------------------")
	return nil
}
